package org.wisdom.data.jpa.id;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.springframework.util.StringUtils;
import org.wisdom.data.jpa.entity.BaseEntity;

import java.io.Serializable;
import java.util.UUID;

/**
 * 主键生成策略
 *
 * @author zhangzhiyan
 * @date 2021/06/24 21:59
 **/
@SuppressWarnings("unused")
public class WisdomIdGenerator implements IdentifierGenerator {

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        BaseEntity baseEntity = (BaseEntity)object;
        if (StringUtils.hasLength(baseEntity.getId())) {
            return baseEntity.getId();
        } else {
            return UUID.randomUUID().toString().replace("-", "");
        }
    }
}
